import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/entity/my_exam_order_entity.dart';
import 'package:panda/home/ChildListOrder.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/DateUtils.dart';
import 'package:panda/util/SignUtil.dart';

class ChildOfShoudanPage extends StatefulWidget {
  var type;
  ChildOfShoudanPage({Key key, @required this.type}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return ChildOfShoudanFragmentState();
  }
}

class ChildOfShoudanFragmentState extends State<ChildOfShoudanPage>
    with WidgetsBindingObserver, AutomaticKeepAliveClientMixin {
  final SlidableController slidableController = SlidableController();

  EasyRefreshController _controller = new EasyRefreshController();
  int currentStatus = 0;
  bool isSelectAll = false;
  var time1 = "", time2 = "", time3 = "", time4 = "", current = "";

  String token = "";
  int page = 1;
  List<MyExamOrderDataData> dataList = new List();
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      getString(TOKEN).then((value) {
        token = value;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      loadList();
    });
    var today = DateTime.now();
    var fiftyDaysFromNow = today.subtract(new Duration(days: 0));
    time1 = DateUtils.instance.getFormartData(
        timeSamp: fiftyDaysFromNow.millisecondsSinceEpoch,
        format: "yyyy-MM-dd");
    current = time1;
    fiftyDaysFromNow = today.subtract(new Duration(days: 1));
    time2 = DateUtils.instance.getFormartData(
        timeSamp: fiftyDaysFromNow.millisecondsSinceEpoch,
        format: "yyyy-MM-dd");
    fiftyDaysFromNow = today.subtract(new Duration(days: 2));
    time3 = DateUtils.instance.getFormartData(
        timeSamp: fiftyDaysFromNow.millisecondsSinceEpoch,
        format: "yyyy-MM-dd");
    setState(() {});
    WidgetsBinding.instance.addObserver(this);
  }

  loadList() async {
    Map map = new Map();
    map['token'] = token;
    map['type'] = widget.type;
    map['p'] = page;
    map['per'] = 10;
    map['date'] = current;
    map['sign_type'] = SignType.TEMP;
    Response<String> response =
        await HttpUtil().post(Api.TEMP, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] != 1) {
      Fluttertoast.showToast(msg: userMap['msg']);
      return;
    }
    MyExamOrderEntity homeListEntity = new MyExamOrderEntity.fromJson(userMap);
    if (mounted)
      setState(() {
        if (page == 1) {
          dataList.clear();
          dataList.addAll(homeListEntity.data.datas);
        } else {
          dataList.addAll(homeListEntity.data.datas);
        }
        if (page == 1) {
          _controller.resetLoadState();
          _controller.finishRefresh();
        } else {
          _controller.finishLoad(noMore: homeListEntity.data.datas.length == 0);
          if (homeListEntity.data.datas.length == 0) {
            Fluttertoast.showToast(msg: "暂无更多数据");
          }
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return AnnotatedRegion<SystemUiOverlayStyle>(
        child: Column(
          children: <Widget>[
            Offstage(
              offstage: widget.type == 1,
              child: Container(
                color: f0Color,
                padding: EdgeInsets.all(10),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      flex: 1,
                      child: GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          child: Container(
                            padding: EdgeInsets.all(
                                ScreenUtil.getInstance().setHeight(DP_10)),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                color:
                                    current == time1 ? Colors.red[100] : grey,
                                borderRadius: BorderRadius.circular(5)),
                            child: Text(time1,
                                style: TextStyle(
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(SMALL_FONT_SIZE),
                                    color: current == time1
                                        ? mainColor
                                        : Colors.black87)),
                          ),
                          onTap: () {
                            current = time1;
                            setState(() {});
                            page=1;
                            loadList();
                          }),
                    ),
                    Container(
                      width: ScreenUtil.getInstance().setHeight(DP_10),
                    ),
                    Expanded(
                      flex: 1,
                      child: GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          child: Container(
                            padding: EdgeInsets.all(
                                ScreenUtil.getInstance().setHeight(DP_10)),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                color:
                                    current == time2 ? Colors.red[100] : grey,
                                borderRadius: BorderRadius.circular(5)),
                            child: Text(time2,
                                style: TextStyle(
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(SMALL_FONT_SIZE),
                                    color: current == time2
                                        ? mainColor
                                        : Colors.black87)),
                          ),
                          onTap: () {
                            current = time2;
                            setState(() {});
                              page=1;
                            loadList();
                          }),
                    ),
                    Container(
                      width: ScreenUtil.getInstance().setHeight(DP_10),
                    ),
                    Expanded(
                      flex: 1,
                      child: GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          child: Container(
                            padding: EdgeInsets.all(
                                ScreenUtil.getInstance().setHeight(DP_10)),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                color:
                                    current == time3 ? Colors.red[100] : grey,
                                borderRadius: BorderRadius.circular(5)),
                            child: Text(time3,
                                style: TextStyle(
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(SMALL_FONT_SIZE),
                                    color: current == time3
                                        ? mainColor
                                        : Colors.black87)),
                          ),
                          onTap: () {
                            current = time3;
                            setState(() {});
                              page=1;
                            loadList();
                          }),
                    ),
                    Container(
                      width: ScreenUtil.getInstance().setHeight(DP_10),
                    ),
                    GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        child: Row(
                          children: <Widget>[
                            Text("全部",
                                style: TextStyle(
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(NORMAL_FONT_SIZE - 2),
                                    color: current == ""
                                        ? mainColor
                                        : Colors.black)),
                            Icon(Icons.arrow_drop_down,
                                color:
                                    current == "" ? mainColor : Colors.black),
                          ],
                        ),
                        onTap: () {
                          current = "";
                          setState(() {});
                            page=1;
                            loadList();
                        })
                  ],
                ),
              ),
            ),
            Expanded(
              child: new EasyRefresh(
                controller: _controller,
                header: MaterialHeader(),
                footer: MaterialFooter(),
                enableControlFinishLoad: false,
                enableControlFinishRefresh: true,
                child: ListView.separated(
                  itemCount: dataList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return renderView(context, index);
                  },
                  separatorBuilder: (BuildContext context, int index) {
                    return Container(height: 10);
                  },
                ),
                onRefresh: () {
                  page = 1;
                  loadList();
                },
                onLoad: () {
                  page++;
                  loadList();
                },
              ),
            ),
            Container(
              height: 0.5,
              color: f0Color,
            ),
            // Offstage(
            //   offstage: widget.type != 1,
            //   child: Container(
            //     color: white,
            //     padding: EdgeInsets.fromLTRB(
            //         ScreenUtil.getInstance().setHeight(5),
            //         ScreenUtil.getInstance().setHeight(DP_10),
            //         ScreenUtil.getInstance().setHeight(DP_20),
            //         ScreenUtil.getInstance().setHeight(DP_10)),
            //     child: Row(
            //       children: <Widget>[
            //         CircularCheckBox(
            //             value: isSelectAll,
            //             activeColor: mainColor,
            //             inactiveColor: black_99,
            //             materialTapTargetSize: MaterialTapTargetSize.padded,
            //             onChanged: (bool x) {
            //               isSelectAll = !isSelectAll;
            //               setState(() {});
            //             }),
            //         Text('全选',
            //             style: TextStyle(
            //                 fontSize:
            //                     ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
            //                 color: Colors.black87)),
            //         Container(
            //           width: 20,
            //         ),
            //         Text(currentStatus == 0 ? '合计：' : '',
            //             style: TextStyle(
            //                 fontSize: ScreenUtil.getInstance()
            //                     .setSp(NORMAL_FONT_SIZE),
            //                 color: Colors.black)),
            //         Text(currentStatus == 0 ? ('5单') : '',
            //             style: TextStyle(
            //                 fontSize: ScreenUtil.getInstance()
            //                     .setSp(NORMAL_FONT_SIZE),
            //                 color: mainColor)),
            //         Expanded(
            //           child: Text(''),
            //         ),
            //         new Container(
            //           height: ScreenUtil.getInstance().setHeight(DP_60),
            //           decoration: new BoxDecoration(
            //               color: mainColor,
            //               borderRadius: BorderRadius.circular(20.0)),
            //           padding: EdgeInsets.fromLTRB(5.0, 0.0, 5.0, 0.0),
            //           child: new FlatButton(
            //             child: new Padding(
            //               padding: EdgeInsets.all(0.0),
            //               child: new Text(
            //                 currentStatus == 0 ? "确认下单" : '删除',
            //                 style: new TextStyle(
            //                     color: Colors.white,
            //                     fontSize: ScreenUtil.getInstance()
            //                         .setSp(NORMAL_FONT_SIZE)),
            //               ),
            //             ),
            //             onPressed: () {},
            //           ),
            //         )
            //       ],
            //     ),
            //   ),
            // )
          ],
        ),
        value: SystemUiOverlayStyle.dark,
    );
  }

  Widget renderView(BuildContext context, int index) {
    return new GestureDetector(
      onTap: () {
        // Navigator.of(context).push(MaterialPageRoute(builder: (context) {
        //   return new OrderDetailPage(
        //     id: dataList[index].id,
        //   );
        // }));
      },
      child: new Container(
        decoration: BoxDecoration(
            color: Colors.white, borderRadius: BorderRadius.circular(0.0)),
        padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              children: <Widget>[
                ClipOval(
                  child: dataList[index].head_img == null
                      ? Image.asset("images/app_icon.png",
                          width: ScreenUtil.getInstance().setHeight(DP_60),
                          height: ScreenUtil.getInstance().setHeight(DP_60),
                          fit: BoxFit.cover)
                      : CachedNetworkImage(
                imageUrl:
                          dataList[index].head_img.contains("http")
                              ? dataList[index].head_img
                              : Api.ImgBaseUrl + dataList[index].head_img,
                          width: ScreenUtil.getInstance().setHeight(DP_60),
                          height: ScreenUtil.getInstance().setHeight(DP_60),
                          fit: BoxFit.cover),
                ),
                Container(width: 10),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        new Text(
                          dataList[index].name == null
                              ? ""
                              : dataList[index].name,
                          style: new TextStyle(
                              color: black,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE)),
                        ),
                        Container(width: 5),
                        Container(
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(2),
                              border: Border.all(color: mainColor, width: 1)),
                          padding: EdgeInsets.fromLTRB(
                              ScreenUtil.getInstance().setHeight(DP_8),
                              0,
                              ScreenUtil.getInstance().setHeight(DP_8),
                              0),
                          margin: EdgeInsets.fromLTRB(0, 0,
                              ScreenUtil.getInstance().setHeight(DP_10), 0),
                          child: Text(
                            dataList[index].group_name == null
                                ? ""
                                : dataList[index].group_name,
                            style: TextStyle(
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(MINI_FONT_SIZE),
                                color: mainColor),
                          ),
                        )
                      ],
                    ),
                    Container(height: 3),
                    new Text(
                      dataList[index].create_time,
                      style: new TextStyle(
                          color: Colors.black45,
                          fontSize:
                              ScreenUtil.getInstance().setSp(MINI_FONT_SIZE)),
                    ),
                  ],
                ),
                Expanded(
                  child: Center(),
                ),
              ],
            ),
            Container(height: 10),
            GestureDetector(
              child: Container(
                padding: EdgeInsets.fromLTRB(30, 20, 30, 20),
                decoration: BoxDecoration(
                  color: f0Color,
                  borderRadius: BorderRadius.circular(5),
                ),
                child: Row(
                  children: <Widget>[
                    new Text(
                      "总额:   ",
                      style: new TextStyle(
                          color: Colors.black54,
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                    ),
                    new Text(
                      MONEY + dataList[index].allprice.toString(),
                      style: new TextStyle(
                          color: mainColor,
                          fontSize:
                              ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
                    ),
                    Container(width: 30),
                    new Text(
                      "单数:   ",
                      style: new TextStyle(
                          color: Colors.black54,
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                    ),
                    new Text(
                      dataList[index].num,
                      style: new TextStyle(
                          color: mainColor,
                          fontSize:
                              ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
                    ),
                    new Text(
                      "个",
                      style: new TextStyle(
                          color: Colors.black54,
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                    ),
                  ],
                ),
              ),
              onTap: () {
                Navigator.of(context)
                    .push(new MaterialPageRoute(builder: (context) {
                  return new ChildOrderListPage(
                      id: dataList[index].parameter,
                      type: widget.type.toString());
                }));
              },
              behavior: HitTestBehavior.opaque,
            ),
            Container(
              height: 10,
            ),
            Row(
              children: <Widget>[
                Expanded(
                  child: new Text(
                    "积分兑换:"+dataList[index].point,
                    style: new TextStyle(
                        color: Colors.black87,
                        fontSize: ScreenUtil.getInstance()
                            .setSp(SMALL_FONT_SIZE + 2)),
                  ),
                ),
                new Text(
                  (widget.type ==2 ? '已收金额' : "应收总额: ") +
                      formatNum((double.parse(dataList[index].allprice)-double.parse(dataList[index].point)),2),
                  style: new TextStyle(
                      color: Colors.black87,
                      fontSize:
                          ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE + 2)),
                ),
              ],
            ),
            Row(
              children: <Widget>[
                Expanded(
                  child: Center(),
                ),
                Offstage(
                    offstage: widget.type != 1,
                    child: new GestureDetector(
                      child: Container(
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                            border: Border.all(color: mainColor, width: 1)),
                        padding: EdgeInsets.fromLTRB(
                            ScreenUtil.getInstance().setHeight(DP_15),
                            3,
                            ScreenUtil.getInstance().setHeight(DP_15),
                            3),
                        margin: EdgeInsets.fromLTRB(
                            0, 10, ScreenUtil.getInstance().setHeight(0), 0),
                        child: Row(
                          children: <Widget>[
                            Text(
                              "收单",
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE),
                                  color: mainColor),
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        showDialog(
                          context: context,
                          builder: (context) => new AlertDialog(
                            title: new Text('提示'),
                            content: new Text('确认收单吗，确认后不可撤回'),
                            actions: <Widget>[
                              new FlatButton(
                                onPressed: () =>
                                    Navigator.of(context).pop(false),
                                child: new Text(
                                  '取消',
                                  style: TextStyle(color: Colors.grey),
                                ),
                              ),
                              new FlatButton(
                                onPressed: () {
                                  // del(index);
                                  Navigator.of(context).pop(false);
                                  shoudan(index);
                                },
                                child: new Text('确定收单',
                                    style: TextStyle(color: mainColor)),
                              ),
                            ],
                          ),
                        );
                      },
                    )),
              ],
            ),
          ],
        ),
      ),
    );
  }

  String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      return num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    } else {
      return num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    }
  }
  shoudan(int index) async {
    Map map = new Map();
    map['token'] = token;
    map['parameter'] = dataList[index].parameter;
    map['sign_type'] = SignType.ORDEREXAMINE;
    Response<String> response =
        await HttpUtil().post(Api.OrderExamine, data: getSign(map));
    Map userMap = json.decode(response.data);
    Fluttertoast.showToast(msg: userMap['msg']);

    if (userMap['code'] == 1) {
      dataList.removeAt(index);
      setState(() {});
    }
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this); //销毁观���者
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return false;
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
